﻿namespace EasyDDD.AdminModule.Application.QueriesSysMenu
{
    public record SysMenuGetListQuery : IQuery<List<SysMenuGetListQueryResult>>
    {
        /// <summary>
        /// 父导航ID
        /// </summary>
        [Comment("父导航ID")]
        public Guid? ParentId { get; set; }

        /// <summary>
        /// 菜单类型（0目录 1菜单 2按钮 3链接）
        /// </summary>
        [Comment("菜单类型")]
        public short[]? MenuType { get; set; }

        /// <summary>
        /// 标题
        /// </summary>
        [Comment("标题")]
        [StringLength(50)]
        public string? Title { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        [Comment("状态")]
        public byte? Status { get; set; }
    }

    [AutoMapperFrom(typeof(Models.SysMenu))]
    public record SysMenuGetListQueryResult : Models.SysMenu
    {
        /// <summary>
        /// 软删除
        /// </summary>
        [NotMapped]
        public override bool IsDeleted { get; set; } = default!;

        /// <summary>
        /// 租户ID
        /// </summary>
        [NotMapped]
        public override Guid TenantId { get; set; } = default!;
    }

    public class SysMenuGetListQueryHandler(
        Records.SysMenuRecords records,
        IMapper mapper,
        ILogger<SysMenuGetListQueryHandler> logger)
        : IQueryHandler<SysMenuGetListQuery, List<SysMenuGetListQueryResult>>
    {
        public Task<List<SysMenuGetListQueryResult>> Handle(SysMenuGetListQuery request, CancellationToken cancellationToken)
        {
            logger.LogDebug("查询 SysMenuGetListQueryHandler");
            var query = records.AsQueryable();
            if (request.ParentId != null)
            {
                query = query.Where(e => e.ParentId == request.ParentId.Value);
            }
            if (request.MenuType != null)
            {
                query = query.Where(e => request.MenuType.Contains(e.MenuType));
            }
            if (request.Status != null)
            {
                query = query.Where(e => e.Status == request.Status.Value);
            }
            if (!string.IsNullOrEmpty(request.Title))
            {
                query = query.Where(e => e.Title.Contains(request.Title));
            }

            query = query.OrderBy(e => e.Id);
            return mapper.ProjectTo<SysMenuGetListQueryResult>(query).ToListAsync(cancellationToken);
        }
    }
}
